﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrackSystem.Contracts;
using TrackSystem.IO.Equip;
using TrackSystem.IO.Logics;
using TrackSystem.IO.Utils;

namespace TrackSystem.IO.Loops
{
    /// <summary>
    /// 调节回路工程类
    /// </summary>
    public class LoopFactory
    {
        public static LoopFactory Instance { get; private set; }

        /// <summary>
        /// 逻辑字典集合
        /// </summary>
        public ConcurrentDictionary<string, LoopItem> Items = new();

        /// <summary>
        /// ID号和逻辑名称对照表
        /// </summary>
        public ConcurrentDictionary<int, string> IdNameDictionary = new();

        /// <summary>
        /// 构造函数
        /// </summary>
        static LoopFactory()
        {
            Instance = new LoopFactory();
        }

        /// <summary>
        /// 卸载所有回路
        /// </summary>
        public  void Unload()
        {
            foreach (var item in Items.Values)
            {
                item.Dispose();
            }
            foreach (var item in Items.Values)
            {
                if (EquipFactory.Instance.TryGetValue(item.EquipId, out var equip))
                {
                    equip?.Parts?.TryRemove(item.Name, out _);
                }
            }
            Items.Clear();
            IdNameDictionary.Clear();
        }

        /// <summary>
        /// 控制回路载入
        /// </summary>
        /// <param name="wrapper"></param>
        /// <returns></returns>
        public async Task<ResultMsg> Load(IRepositoryWrapper wrapper)
        {
            Unload();

            try
            {
                var loopList = await wrapper.Loop.GetAllListAsync();
                foreach (var loop in loopList)
                {
                    var loopItem = new LoopItem();
                    loopItem.Init(loop);
                    Items.TryAdd(loop.Name, loopItem);
                    IdNameDictionary.TryAdd(loop.Id, loop.Name);
                    
                    if (EquipFactory.Instance.TryGetValue(loopItem.EquipId, out EquipItem? equipItem))
                    {
                        equipItem.TryAddLoop(loopItem);
                    }
                }
                return ResultMsg.Succ("初始化控制回路成功");
            }
            catch (Exception ex)
            {
                return ResultMsg.Fail($"初始化控制回路失败, {ex.Message}");
            }
        }
    }
}
